#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
int main(int argc, char *argv[])
{
  int fpin, fpout;
  off_t res;
  off_t filesize;
  int cycle_length;
  int step;
  unsigned char current_byte = 0;
  int i,pos,temp,sin_pos;
  float tempfloat;

  if(argc < 5)
  {
    printf("please use %s cycle_length step inputfile.gray outputfile.gray\n", argv[0]);
    return 1;
  }
  cycle_length  = atoi(argv[1]);
  step  = atoi(argv[2]);

  fpin = open(argv[3], O_RDONLY);
  if(fpin < 0)
  {
    printf("input file %s could not be opened\n", argv[3]);
    return 2;
  }
  fpout = open(argv[4], O_CREAT|O_RDWR|O_TRUNC,S_IRUSR|S_IWUSR);
  if(fpout < 0)
  {
    printf("output file %s could not be opened\n", argv[4]);
    return 2;
  }
  filesize = lseek(fpin, 0L, SEEK_END);
  if(filesize < 0)
  {
    perror("fseek1");
    return 3;
  }
  res = lseek(fpin, (off_t)0, SEEK_SET);
  if(res < 0)
  {
    perror("fseek2");
    return 4;
  }

  printf("inputfile has %0ld bytes, cycle_length %0d, step %0d\n", filesize, cycle_length, step);
  pos=0;
  for(i=0;i<filesize;i++)
  {
    if(read(fpin, &current_byte, 1)<0)
    {
      perror("read");
      return 5;
    }
    sin_pos = pos%cycle_length;
    temp = 204 - current_byte;
    if(step > 1)
    {
      tempfloat = (0.16 + temp*0.64/204)*sin(2*3.1412*sin_pos/cycle_length);
      current_byte = 127 + tempfloat * 128;
    }
    else
    {
      current_byte = temp;
    }
    if(write(fpout, &current_byte, 1)<0)
    {
      perror("write");
      return 5;
    }
    pos++;
  }
  close(fpin);
  close(fpout);
  return 0;
}
